﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using PSE.Deployment.ConfigurationManager.Controls;
using PSE.Deployment.SetupBase;
using PSE.Deployment.Util;
using Sinacor.Deployment.Setup.Main;

namespace Sinacor.Deployment.Setup.UI
{
    /// <summary>
    /// Interaction logic for BancoDadosPassoA.xaml
    /// </summary>
    public partial class DataBaseConnection : BaseDataBaseWizardWindow
    {
        #region Fields
        private bool CheckConnection = false;
        #endregion

        #region Construtor
        public DataBaseConnection()
        {
            this.InitializeComponent();
            this.DataContext = SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo;
            this.Loaded += new RoutedEventHandler(DataBaseConnection_Loaded);

        }
        #endregion

        #region Eventos Window
        void DataBaseConnection_Loaded(object sender, RoutedEventArgs e)
        {
            GetTNS(CboTNS);
            CheckAllowNext();
            LoadConfiguration();
            CheckConnection = true;
        }
        #endregion

        #region Método de Habilitação do Botão Próximo
        private void CheckAllowNext()
        {
            this.AllowNext = SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection;
        }
        #endregion

        #region Eventos e Métodos do Teste de Conexão
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (String.IsNullOrEmpty(CboTNS.Text))
            {
                ConfigurationMessageBox.Show("Digite o TNS para realizar o teste de conexão!", "Atenção", ConfigurationMessageBoxButton.Ok, ConfigurationMessageBoxImage.Information);
                CboTNS.Focus();
                return;
            }

            if (String.IsNullOrEmpty(TxtUser.Text))
            {
                ConfigurationMessageBox.Show("Digite o usuário para realizar o teste de conexão!", "Atenção", ConfigurationMessageBoxButton.Ok, ConfigurationMessageBoxImage.Information);
                TxtUser.Focus();
                return;
            }

            if (String.IsNullOrEmpty(TxtPassword.Password))
            {
                ConfigurationMessageBox.Show("Digite a senha para realizar o teste de conexão !", "Atenção", ConfigurationMessageBoxButton.Ok, ConfigurationMessageBoxImage.Information);
                TxtPassword.Focus();
                return;
            }

            if (TestConnection(TxtUser.Text, TxtPassword.Password, CboTNS.Text, ChkEncryptedPassword.IsChecked.GetValueOrDefault()))
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection = true;
                ConfigurationMessageBox.Show("Teste de Conexão realizado com Sucesso!", "Mensagem Setup Sinacor", ConfigurationMessageBoxButton.Ok, ConfigurationMessageBoxImage.Information);
            }
            else
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists = false;
                ConfigurationMessageBox.Show("Ocorreu um erro no teste de conexão!" + Environment.NewLine + "Erro: " + SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionTestingException, "Atenção", ConfigurationMessageBoxButton.Ok, ConfigurationMessageBoxImage.Error);

            }
            
            CheckAllowNext();
        }

        #endregion

        #region Eventos dos Botões Próximo e Anterior
        protected override void OnPreviousClick(RoutedEventArgs e)
        {
            base.OnPreviousClick(e);
            SaveConnectionInfo();
        }

        protected override void OnNextClick(RoutedEventArgs e)
        {
            base.OnNextClick(e);

            if (!SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.GoNextNoTestingConnection)
            {
                if (!SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection && ConfigurationMessageBox.Show("Deseja realmente prosseguir sem Testar a Conexão?", "Atenção", ConfigurationMessageBoxButton.YesNo, ConfigurationMessageBoxImage.Question) == ConfigurationMessageBoxResult.No)
                    e.Handled = true;
                else
                    SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.GoNextNoTestingConnection = true;
            }

            PSE.Deployment.SetupBase.Configuration.Group group = SetupMainFactory.GetInstance<SinacorMain>().Configuration.SystemInfo.Groups.SelectDeep(g => g.SubGroups).ToList().Find(g => g.Id == "Database");

            if (!SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase && (group != null && (group.Install == null || group.Install.GetValueOrDefault())))
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists = DataBaseSinacorExists(TxtUser.Text, TxtPassword.Password, CboTNS.Text, ChkEncryptedPassword.IsChecked.GetValueOrDefault());
                if (SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists)
                {
                    if (ConfigurationMessageBox.Show("ATENÇÃO: Já existe uma versão do Banco de Dados SINACOR instalada!" + Environment.NewLine + "Ao confirmar esta operação as tabelas serão reinstaladas.", "Atenção", ConfigurationMessageBoxButton.OkCancel, ConfigurationMessageBoxImage.Question) == ConfigurationMessageBoxResult.Cancel)
                    {
                        SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = false;
                        e.Handled = true;
                    }
                    else
                    {
                        SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = true;
                    }
                }
            }

            SaveConnectionInfo();


        }
        #endregion

        #region Métodos de Load e Save dos Dados de Conexão
        private void SaveConnectionInfo()
        {
            SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.Password = EncryptDecrypt.Encrypt(TxtPassword.Password);
            SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.TNSName = CboTNS.Text;
            SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.User = TxtUser.Text;
        }

        private void LoadConfiguration()
        {
            TxtUser.Text = SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.User;            
            CboTNS.Text = SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.TNSName;

            if (!string.IsNullOrEmpty(SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.Password))
            {
                TxtPassword.Password = EncryptDecrypt.Decrypt(SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.ConnectionInfo.Password);
            }
        }
        #endregion

        #region Evento de TextChanged dos TextBoxes User / Password e TNS
        private void TxtUser_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (CheckConnection)
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = false;
            }

            CheckAllowNext();


        }


        private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (CheckConnection)
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = false;
            }

            CheckAllowNext();

        }

        private void TxtPassword_PasswordChanged(object sender, RoutedEventArgs e)
        {
            if (CheckConnection)
            {
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.TestedConnection = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.SinacorDataBaseExists = false;
                SetupMainFactory.GetInstance<SinacorMain>().Parameter.DataBase.PermitedClearSinacorDataBase = false;
            }

            CheckAllowNext();
        }

        #endregion

    }

}
